
package org.jeecg.modules.friends.base;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Order(100)
@Slf4j
@Aspect
@Component
public class ControllerCommonAspect extends BaseAspect {


    /**
     * Controller入参拦截
     **/
    @Pointcut("execution(* org.jeecg.modules.friends.controller..*(..))")
    public void controllerInParamRecord() {
    }

    /**
     * Controller 入参切面
     */
    @Around("controllerInParamRecord()")
    public Object inParamRecordAround(ProceedingJoinPoint jp) throws Throwable {
        Object result = null;
        HttpReturn<?> failResult = null;
        long startTime = System.currentTimeMillis();
        try {
            // 执行目标方法
            result = jp.proceed();
        } catch (ServiceException e) {
            log.warn("ServiceException[IP:{}]：{}", IpUtils.getClientIP(), e.getMsg());
            failResult = HttpReturn.failResult(e.getMsg());
            return failResult;
        } catch (ParameterException e) {
            log.warn("ParameterException[IP:{}]：{}", IpUtils.getClientIP(), e.getMsg());
            failResult = HttpReturn.failResult(e.getMsg());
            return failResult;
        } catch (Exception e) {
            log.error("error", e);
            // 错误推送
            NotifyTool.weChatAlarm(e);
            return HttpReturn.failResult(e.getMessage());
        } finally {
            try {
                long endTime = System.currentTimeMillis();
                long duration = endTime - startTime;
                String paramJson = this.getParamJson(jp.getArgs());
                String methodQualifiedName = getMethodQualifiedName(jp);

                if (!methodQualifiedName.contains("heartbeat")) {
                    log.info("{}, request[{}] param===> {},Response===> {},cost {} ms", IpUtils.getClientIP(),
                            methodQualifiedName,
                            paramJson, // 请求参数
                            failResult != null ? JSON.toJSON(failResult) : JSON.toJSONString(result), duration);
                }
            } catch (Exception e) {
                log.error("error.eeee", e);
            }
        }
        return result;
    }

    private String getParamJson(Object[] args) {
        try {
            return JSON.toJSONString(args);
        } catch (Exception e) {
            log.error("error:{}", e.getMessage());
            return "";
        }
    }

}
